<?php
namespace app\wap\controller;

use app\api\controller\KbxOrder;
use think\Controller;
use app\api\model\GroupToursLine as GT;
use app\api\model\Order as OrderModel;

class Grouptoursline extends Controller{
    //初始化
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
    }
    //获取线路列表
    public function getGroupToursList()
    {
        $post = request()->post();
        $city_id = $post['city_id']??0;
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $model = new GT();
        list($total,$list) = $model->getList($city_id,$page,$offset,'wap');
        //封装线路的成团情况 to do ...
        foreach ($list as $key=>$value){
            $list[$key]['groupOrder'] = $model->getOrderToursGroup($value['line_id']);
        }
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //获取线路详情
    public function getGroupToursInfo()
    {
        $post = request()->post();
        $line_id = $post['line_id']??0;
        $model = new GT();
        $detail = $model->getDetail($line_id,'wap',true);
        if(empty($detail)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else {
            $groupOrder = $model->getOrderToursGroup($line_id);
            //成团情况 to do ....
            $detail['groupOrder'] = $groupOrder;
            return json_encode(['code' => 200, 'msg' => 'success', 'data' => $detail]);
        }
    }

    //获取首页推荐拼团
    public function getRecommendGroupTours()
    {
        $model = new GT();
        $list = $model->recommendGroupTours();
        $exchange = db('exchange')->select();
        if(!empty($list)){
            foreach ($list as $key=>$value){
                unset($list[$key]['from_address_json'],$list[$key]['to_address_json']);
                $exchange_rate = 1;
                foreach ($exchange as $e_v){
                    if($e_v['currency_code']==$value['currency']){
                        $exchange_rate = $e_v['exchange_rate'];
                    }
                }
                $list[$key]['person_price_currency'] = ((new GT())->getSymbolByCurrency($value['currency']))['currSymbol'];
                $list[$key]['person_price_cny'] = sprintf('%.0f',$value['person_price']*$exchange_rate);
                $list[$key]['groupOrder'] = $model->getOrderToursGroup($value['line_id']);
            }
        }
        return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    //订单加人接口
    public function addCustomerToOrder()
    {
        $post = request()->post();
        //检验必须参数 to do ...
        $match_arr = array(
            "consumer_phone",
            "adultPassengers",
            "line_id",
            "member_id",
        );
        $match_res = $this->match_post($match_arr,$post);
        if($match_res['code']!=200){
            return json_encode($match_res);
        }
        //推广人id
        $post['spread_member_id'] = $post['spread_member_id']??0;
        //发送到订单系统
        $kbxOrder = new KbxOrder();
        //如果用户发起拼团
        $order_data = [];
        if(!isset($post['carPoolOrder']) || empty($post['carPoolOrder'])){

            $startDate = $post['startDate']??"";
//            $person_id = $post['person_id']??0;
//            $personInfo = db("person")->find($person_id);
            if(empty($startDate)){
                return json_encode(['code'=>-1,'msg'=>'请选择出行时间']);
            }
//            if(empty($personInfo)){
//                return json_encode(['code'=>-1,'msg'=>'请选择拼团类型']);
//            }
            $personInfo = [];
            $model = new GT();
            $detail = $model->getDetail($post['line_id'],'wap',true);
            if(empty($detail)){
                return json_encode(['code'=>-1,'msg'=>'拼团线路有误']);
            }
            $order_data = $this->getOrderDataByGroupLineDetail($startDate,$personInfo,$post,$detail);
        }
        $res = $kbxOrder->addCustomerByMall($post,$order_data);
//        var_dump($res);exit;
        //解析订单系统的结果
        if(isset($res['carPoolOrder']['_id']) && !empty($res['carPoolOrder']['_id'])){
            $data = ['code'=>200,'msg'=>'success','data'=>$res];
            //给后台管理员发邮件
            $orderDate = array(
                'line_id'=>$res['carPoolOrder']['line'],
                'member_id'=>$res['personalOrder']['booker']['memberId'],
                'order_no'=>$res['personalOrder']['orderNo'],
//                'e_mail'=>$res['personalOrder']['consumer']['contact']['email'],
                'phone'=>$res['personalOrder']['consumer']['contact']['phone'],
                "travel_date"=>$res['carPoolOrder']['details']['startDate'],
            );
            (new Notify())->gyouxiang($orderDate,"carPool",'新小V拼游订单通知【未支付】');
            //推广人员记录佣金
            //前端uid参数转换成spread_member_id
            $post['spread_member_id'] = $post['uid']??0;
            (new OrderModel())->shareCashBackToSpreadMember($post,$res);
        }elseif(isset($res['msg'])){
            $data = ['code'=>-1,'msg'=>$res['msg']];
        }else{
            $data = ['code'=>-2,'msg'=>'加入拼团失败，请稍后重试！'];
        }

        return json_encode($data);
    }

    /**
     * 验证POST数组中是否存在要求的字段并且不能为空
     * By Max
     * 2019/06/20
     */
    public function match_post($match_arr=array(),$post=array())
    {
        if(!empty($post)){
            $key = array_keys($post);
            foreach($match_arr as $value){
                if(!in_array($value,$key)){//POST数组中不存在要求的key时
                    return array('code'=>400,'msg'=>'missKey is '.$value);
                }elseif(empty($post[$value])){
                    return array('code'=>402,'msg'=>$value.' is empty');
                }
            }
        }else{
            return array('code'=>401,'msg'=>'data is empty');
        }
        return array('code'=>200,'msg'=>'success');
    }

    public function getOrderDataByGroupLineDetail($startDate,$personInfo,$post,$detail)
    {
        $order_data = [];
        $exchange = db('exchange')->select();
        $exchange_rate = 1;
        foreach ($exchange as $e_v){
            if($e_v['currency_code']==$detail['currency']){
                $exchange_rate = $e_v['exchange_rate'];break;
            }
        }
        $packages = (new GT())->getPackageSpecByLineId($detail['line_id'],$exchange_rate);
        $maxPersonNum = 0;
        foreach ($packages as $p_k=>$p_v){
            foreach ($p_v['child'] as $c_k=>$c_v){
                if($c_v['num'] > $maxPersonNum){
                    $maxPersonNum = $c_v['num'];
                }
            }
        }
        if(!empty($detail) && isset($detail['product_info']) && isset($detail['tripInfo'])){
            $endDate = date("Y-m-d",strtotime("-".$detail['end_days']."day",strtotime($startDate)));
            $unitPrice = !empty($detail['person_price'])?sprintf('%.2f',$detail['person_price']*$exchange_rate):($personInfo['person_price']??0);
            $maxPartySize = $maxPersonNum>0?$maxPersonNum:$personInfo['person_num'];
            $totalPrice = $maxPartySize*$unitPrice;
            $hotel_num = $post['hotel_num'];
            $totalHotelPrice = $hotel_num*$detail['hotel_days']*$detail['hotel_unit_price'];
            $order_data = [
                'name'=>$detail['title'],
                'type'=>'fullday',
                'subType'=>$detail['subType'],
                'line'=>$detail['line_id'],
                'maxPartySize'=>$maxPartySize,
                'details'=>[
                    'fromCity'=>$detail['kbx_id'],
                    'startDate'=>$startDate,
                    'carType'=>$detail['carType'],
                    'itinerary'=>$detail['toursLineTitle'],
                    'days'=>$detail['days'],
                    'specialInfo'=>$detail['specialInfo'],
                    'hotel_unit_price'=>$detail['hotel_unit_price'],
                    'hotel_days'=>$detail['hotel_days'],
                    "nights"=>$detail['hotel_days'],
                    "from"=>$detail['from'],
                    "to"=>$detail['to'],
                ],
                "status"=>'open',
                "payDeadline"=>$endDate,
                "price"=>[
                    'unitPrice'=>$unitPrice,
                    "unitHotelPrice"=>$detail['hotel_unit_price'],
                    'totalPrice'=>$totalPrice,
                    'totalHotelPrice'=>$totalHotelPrice,
                    'unitTicketPrice'=>$detail['unitTicketPrice'],
                    'carPrice'=>$detail['carPrice'],
                ],
            ];
        }
        return $order_data;
    }

    //获取拼团产品的套餐价
    public function getGroupSpecPrice()
    {
        $post = request()->post();
        $date = $post['date']??"";
        $line_id = $post['line_id']??0;
        $line = db("group_tours_line")->find($line_id);
        if(empty($line)){
            return json_encode(['code'=>-1,'msg'=>'线路信息不存在']);
        }
        $model = new GT();
        $priceList = $model->getGoodsSpecPriceByDate($line['product_id'],$date);
        if(empty($priceList)){
            return json_encode(['code'=>-1,'msg'=>'套餐暂未配置']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$priceList]);
        }
    }

    /**
     * 获取酒店房价列表
     */
    public function getGroupRoomPrice()
    {
        $post = request()->post();
        if(empty($post['line_id'])){
            return json_encode(['status'=>-1,'msg'=>'缺少参数line_id']);exit;
        }else{
            $line_id = $post['line_id'];
        }
        $model = new GT();
        $list = $model->getRoomPrice($line_id);

        return json_encode(['status'=>200,'msg'=>'success','data'=>$list]);exit;
    }
}
